package cn.net.yto.school.web.file;

import cn.net.yto.base.dao.entities.TAccount;
import cn.net.yto.base.dao.pagination.PaginationRequest;
import cn.net.yto.base.dao.pagination.PaginationResponse;
import cn.net.yto.base.shiro.util.ShiroUserHelper;
import cn.net.yto.base.util.RequestHandler;
import cn.net.yto.school.dao.entities.TbFile;
import cn.net.yto.school.service.FileService;
import cn.net.yto.school.web.sparm.StaticParamClazz;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;

@Controller
@RequestMapping("/file")
public class FileCotroller {

    @Autowired
    private FileService fileService;

    @RequestMapping("query")
    public String query(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "file/file_init";
    }

    @RequestMapping("list")
    public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
        PaginationRequest paginationRequest = RequestHandler.buildPaginationRequest(request, model);
        PaginationResponse<TbFile> paginationResponse = this.fileService.findResultsByPagination(paginationRequest);
        model.addAttribute("paginationResponse", paginationResponse);

        return "file/file_list";
    }

    @RequestMapping("delete/{id}")
    public String delete(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") Integer id) {
        this.fileService.deleteFileById(id);

        return "redirect:/file/query";
    }

    @RequestMapping(value = {"edit/{id}"}, method = {RequestMethod.GET})
    public String editClazz(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") Integer id) {
        model.addAttribute("fileEle", this.fileService.findOneById(id));

        return "file/file_edit";
    }

    @RequestMapping(value = {"edit"}, method = {RequestMethod.POST})
    public String editClazzHandler(HttpServletRequest request, HttpServletResponse response, Model model) {

        TbFile file = (TbFile) RequestHandler.createBean(request, new TbFile());

        TAccount account = new TAccount();
        account.setId(ShiroUserHelper.getCurrentShiroUser().getId());
        file.setActor(account);

        this.fileService.saveFile(file);

        return "redirect:/clazz/query";
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, Model model, String filePath, Integer id) throws IOException {
        // 读取文件
        File file = new File(StaticParamClazz.FILE_UPLOAD_ROOT_PATH + File.separator + filePath);
        if (file.exists()) {
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            try {
                response.setContentType("application/octet-stream");
                filePath = URLDecoder.decode(filePath);

                response.setHeader("Content-disposition", "attachment; filename="
                        + new String(filePath.getBytes("utf-8"), "ISO8859-1")); // 指定下载的文件名
                os.write(FileUtils.readFileToByteArray(file));
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }

        TbFile f = this.fileService.findOneById(id);
        f.setFileDownloadCount(f.getFileDownloadCount() + 1);
        this.fileService.saveFile(f);
    }
}
